import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import {
  SimpleTableComponent,
  SimpleTableColumn,
  SimpleTableData,
} from '@delon/abc';
import { FormGroup, Validators, FormBuilder } from '../../../../../node_modules/@angular/forms';
import { CustomerService } from '../customer.service';

@Component({
  selector: 'pro-table-list',
  templateUrl: 'table.component.html',
  styleUrls: ['table.component.css']
})
export class TableComponent implements OnInit {

  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];

  @ViewChild('st') st: SimpleTableComponent;
  @ViewChild('modalContent') modalContent: TemplateRef<{}>;

  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    {
      title: '头像',
      index: 'avatarUrl',
      type: 'img',
    },
    { title: '姓名', index: 'name' },
    { title: '手机', index: 'mobile' },
    {
      title: 'openId',
      index: 'openId'
    },
    {
      title: '昵称',
      index: 'nickName',
    },
    {
      title: '性别',
      index: 'gender',
    },
    {
      title: '省',
      index: 'province'
    },
    {
      title: '市',
      index: 'city'
    },
    {
      title: '创建时间',
      index: 'createTime',
      type: 'date',
    },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          click: (item: any) => this.edit(this.modalContent, item),
        }
      ],
    },
  ];

  selectedRows: SimpleTableData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  form: FormGroup;
  _employee: any;
  fromList: any;
  statusList: any;


  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private fb: FormBuilder,
    private customerService: CustomerService
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      name: [null, [Validators.required]],
      mobile: [null, [Validators.required]],
      weixin: [null, [Validators.required]],
      from: [null, [Validators.required]],
      remarks: [null, []],
      status: [null, [Validators.required]],
    });

    this.getData();

    let temp: any = localStorage.getItem("employee");
    this._employee = JSON.parse(temp);

    this.customerService.getValueListByParentCode("from").subscribe(resp => {
      if(resp.success)
        this.fromList = resp.data;
    })

    this.customerService.getValueListByParentCode("customerStatus").subscribe(resp => {
      if(resp.success)
        this.statusList = resp.data;
    })

  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);
    if (this.q.status !== null && this.q.status > -1)
      this.q.statusList.push(this.q.status);

    this.customerService.query(this.q).subscribe(resp => {
      this.loading = false;
      if (resp.success)
        this.data = resp.data;
      else
        this.data = [];

    }, error => {
      this.loading = false;
      this.msg.error("error: " + JSON.stringify(error));

    });

  }

  checkboxChange(list: SimpleTableData[]) {
    this.selectedRows = list;
    this.totalCallNo = this.selectedRows.reduce(
      (total, cv) => total + cv.callNo,
      0,
    );
  }

  remove() {
    this.http
      .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
      .subscribe(() => {
        this.getData();
        this.st.clearCheck();
      });
  }

  /*
  approval() {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }
  */

  add(tpl: TemplateRef<{}>) {
    this.form.reset();

    this.modalSrv.create({
      nzWidth: 640,
      nzMaskClosable: false,
      nzTitle: '新建',
      nzContent: tpl,
      nzOkText: "提交",
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        this.loading = true;
        this.customerService.create(this.form.value, this._employee.id).subscribe(resp => {
          this.loading = false;
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);

        }, error => {
          this.loading = false;
          this.msg.error("异常: " + JSON.stringify(error));

        });

        return false;
      },
      nzCancelText: null
    });
  }

  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }

  edit(tpl: TemplateRef<{}>, item: any) {
    this.form.reset();
    this.form.setValue({
      name: item.name,
      mobile: item.mobile,
      weixin: item.weixin,
      from: item.from,
      remarks: item.remarks,
      status: item.status,
    });

    this.modalSrv.create({
      nzWidth: 640,
      nzMaskClosable: false,
      nzTitle: '编辑',
      nzContent: tpl,
      nzOkText: "保存",
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        item.name = this.form.value.name;
        item.mobile = this.form.value.mobile;
        item.weixin = this.form.value.weixin;
        item.from = this.form.value.from;
        item.remarks = this.form.value.remarks;
        item.status = this.form.value.status;

        this.loading = true;
        this.customerService.edit(item).subscribe(resp => {
          this.loading = false;
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);

        }, error => {
          this.loading = false;
          this.msg.error("异常: " + JSON.stringify(error));

        });

        return false;
      },
      nzCancelText: null
    });
  }

  delete(item: any): any {
    this.modalSrv.confirm({
      nzTitle: '确认删除么?',
      nzContent: '点击确认，继续删除。点击取消，退出操作！',
      nzOkText: "确定",
      nzCancelText: "取消",
      nzOnOk: () => {
        this.customerService.del(item.id).subscribe(resp => {
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);
        }, error => {
          this.msg.error("异常: " + JSON.stringify(error));
        });
      }
    });

  }

  export(tpl: TemplateRef<{}>) {
    this.modalSrv.create({
      // nzWidth: 320,
      nzMaskClosable: false,
      nzTitle: '导入',
      nzContent: tpl,
      nzOkText: "提交",
      nzOnOk: () => {
        
        return false;
      },
      nzCancelText: null
    });
  }

}
